package com.xiaowen.tool.excle;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

@Slf4j
public class NoModleDataListener extends AnalysisEventListener<Map<Integer, String>> {

    List<Map<Integer, String>> list = new ArrayList<>();
    List<List<String>> headList = new ArrayList<>();
    List<Map<String, Object>> dataList = new ArrayList<>();

    @Override
    public void invoke(Map<Integer, String> data, AnalysisContext analysisContext) {
        log.info("解析到一条数据:{}", JSON.toJSONString(data));
        list.add(data);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        parseHeadData();
        parseBizData();
    }

    /**
     * 解析表头-校验模式格式是否正确用
     */
    public void parseHeadData() {
        Map<Integer, String> headerMap = list.get(0);
        List<String> headers = new ArrayList<>();
        // 按照 key 的大小排序
        TreeMap<Integer, String> sortedMap = new TreeMap<>(headerMap);
        for (Map.Entry<Integer, String> entry : sortedMap.entrySet()) {
            headers.add(entry.getValue());
        }
        headList.add(headers);
    }

    /**
     * 解析业务数据
     */
    public void parseBizData(){
        if (list.size() <= 1) {
            log.info("未获取到业务数据");
            return;
        }

        int dataLength = list.get(0).size();
        //从第三行还是解析数据-前两行是表头
        for (int i = 1; i < list.size(); i++) {
            Map<String, Object> data = Maps.newHashMap();
            // 按照 key 的大小排序
            TreeMap<Integer, String> sortedMap = new TreeMap<>(list.get(i));
            for (Map.Entry<Integer, String> entry : sortedMap.entrySet()) {
                String key = headList.get(0).get(entry.getKey());
                data.put(key, entry.getValue());
            }
            dataList.add(data);
        }
    }

    /**
     * 获取表头
     * @return
     */
    public List<List<String>> getHeadList(){
        return this.headList;
    }

    public List<Map<String, Object>> getDataList(){
        return this.dataList;
    }
}
